package com.lyn.solitude_plugin_host.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.Base64;

import java.io.ByteArrayOutputStream;

/**
 * @author longyn 2024/4/21
 * @version 1.0.0
 */
public class Base64Util {


    public static String drawableToBase64(Drawable drawable) {
        try {
            if (drawable == null){
                return null;
            }
            Bitmap bitmap = drawableToBitmap(drawable);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            String base64 = Base64.encodeToString(outputStream.toByteArray(),
                    Base64.DEFAULT);
            outputStream.close();
            return base64;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap base64ToBitmap(String base64){
       try {
           if (base64 == null){
               return null;
           }
           byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
           return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
       }catch (Throwable e){
           e.printStackTrace();
       }
       return null;
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap;
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }
}
